package com.blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.blog.common.CustomException;
import com.blog.common.Result;
import com.blog.dto.UserDto;
import com.blog.mapper.UserMapper;
import com.blog.pojo.Blog;
import com.blog.pojo.Follow;
import com.blog.pojo.User;
import com.blog.service.BlogService;
import com.blog.service.FollowService;
import com.blog.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 关注与取关
 */
@RestController
@RequestMapping("/follow")
public class FollowController {
    @Autowired
    private FollowService followService;

    @Autowired
    private BlogService blogService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 关注作者
     *
     * @param userId 当前登录的用户的id
     * @param blogId 当前浏览的博客的id
     * @return Result<String>
     */
    @GetMapping("/followOrCancel")
    private Result<String> followOrCancel(Long userId, Long blogId) {
        Blog blogServiceById = blogService.getById(blogId);
        User userServiceByBlogId = userService.getById(blogServiceById.getUserId());
        //博客的作者的id
        Long fatherUserId = userServiceByBlogId.getId();
        LambdaQueryWrapper<Follow> followLambdaQueryWrapper = new LambdaQueryWrapper<>();
        followLambdaQueryWrapper.eq(Follow::getUserId, userId).eq(Follow::getFatherUserId, fatherUserId);
        //
        Follow followServiceOne = followService.getOne(followLambdaQueryWrapper);
        if (followServiceOne == null) {//该用户还未关注该博客的作者
            if (!fatherUserId.equals(userId)) {//关注的不是自己
                //关注操作
                Follow follow = new Follow();
                follow.setUserId(userId);
                follow.setFatherUserId(fatherUserId);
                followService.save(follow);
                return Result.success("关注成功！");
            }
            //不能关注自己
            return Result.error("亲爱的，您不能关注自己哦...");
        }
        //改用户已经关注该博客作者
        //取关操作
        followService.remove(followLambdaQueryWrapper);
        return Result.success("取关成功！");
    }

    /**
     * 判断是否已经关注该博主
     *
     * @param userId   用户id
     * @param fatherId 博客作者id
     * @return Result<Boolean>
     */
    @GetMapping("/isOrNot")
    private Result<Boolean> isOrNot(Long userId, Long fatherId) {
        LambdaQueryWrapper<Follow> followLambdaQueryWrapper = new LambdaQueryWrapper<>();
        followLambdaQueryWrapper.eq(Follow::getUserId, userId).eq(Follow::getFatherUserId, fatherId);
        Follow followServiceOne = followService.getOne(followLambdaQueryWrapper);
        if (followServiceOne != null) {//已经关注
            return Result.success(true);
        }
        //未关注
        return Result.success(false);
    }

    /**
     * 查询我关注的全部博主信息
     *
     * @param userId 用户id
     * @return Result<List<UserDto>>
     */
    @GetMapping("/myFollows")
    private Result<List<UserDto>> myFollows(Long userId) {
        LambdaQueryWrapper<Follow> followLambdaQueryWrapper = new LambdaQueryWrapper<>();
        followLambdaQueryWrapper.eq(Follow::getUserId, userId);
        //查出该user的关注列表
        List<Follow> followList = followService.list(followLambdaQueryWrapper);
        if (followList.size() != 0) {//我有关注至少一个博主
            //遍历列表，获得所有的fatherId
            List<Long> fatherIds = new ArrayList<>();
            for (Follow follow : followList) {
                fatherIds.add(follow.getFatherUserId());
            }
            //根据fatherIds查找所有对应用户信息
            List<User> userList = userMapper.selectBatchIds(fatherIds);
            //将需要的信息封装到dto内
            //List<UserDto> userDtoList = new ArrayList<>();
            List<UserDto> userDtos = userList.stream().map((item) -> {
                UserDto userDto = new UserDto();
            /*userDto.setUsername(item.getUsername());
            userDto.setUserAccount(item.getUserAccount());
            userDto.setAvatarUrl(item.getAvatarUrl());*/
                BeanUtils.copyProperties(item, userDto);
                //因为属性名称不一致，没拷贝成功，所以不一致的还要单独设置
                userDto.setUserId(item.getId());
                return userDto;
            }).collect(Collectors.toList());
            return Result.success(userDtos);
        }
        //未关注任何博主
        return Result.error("您还没有关注任何博主！");
    }

    /**
     * 查询关注了我的所有用户
     *
     * @param userId 用户id
     * @return Result<List<UserDto>>
     */
    @GetMapping("/usersFollowedMe")
    private Result<List<UserDto>> usersFollowedMe(Long userId) {
        LambdaQueryWrapper<Follow> followLambdaQueryWrapper = new LambdaQueryWrapper<>();
        followLambdaQueryWrapper.eq(Follow::getFatherUserId, userId);//构造fatherId条件
        //查出该user的关注列表
        List<Follow> followList = followService.list(followLambdaQueryWrapper);
        if (followList.size() != 0) {//我至少有一个粉丝
            //遍历列表，获得所有的sonId
            List<Long> sonIds = new ArrayList<>();
            for (Follow follow : followList) {
                sonIds.add(follow.getUserId());
            }
            //根据sonIds查找所有对应用户信息
            List<User> userList = userMapper.selectBatchIds(sonIds);
            //将需要的信息封装到dto内
            List<UserDto> userDtos = userList.stream().map((item) -> {
                UserDto userDto = new UserDto();
                BeanUtils.copyProperties(item, userDto);
                //因为属性名称不一致，没拷贝成功，所以不一致的还要单独设置
                userDto.setUserId(item.getId());
                return userDto;
            }).collect(Collectors.toList());
            return Result.success(userDtos);
        }
        //还没有任何粉丝
        return Result.error("您还没有任何粉丝！");
    }

}
